#ifndef INTERATIONBOARD
#define INTERATIONBOARD

#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "datastructure.hpp"
#include "myLog4.h"

#define BUFFER_SIZE 5000

class TCPClient {
public:
    TCPClient(const std::string& server_ip, int server_port) : sockfd(-1) {
        // 创建客户端socket
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0) {
            LOG_ERROR("[log4]" << LOG4CPLUS_TEXT("创建与开发板交互socket失败: "));
            exit(EXIT_FAILURE);
        }

        // 初始化服务器地址结构
        memset(&servaddr, 0, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(server_port);

        // 将IP地址转换为二进制格式并赋值
        if (inet_pton(AF_INET, server_ip.c_str(), &servaddr.sin_addr) <= 0) {
            LOG_ERROR("[log4]" << LOG4CPLUS_TEXT("开发板socket地址解析失败 "));
            close(sockfd);
            exit(EXIT_FAILURE);
        }

        // 连接到服务器
        if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
            LOG_ERROR("[log4]" << LOG4CPLUS_TEXT("socket连接到开发板失败"));
            close(sockfd);
            exit(EXIT_FAILURE);
        }
        LOG_INFO("[log4]" << LOG4CPLUS_TEXT("连接到开发板:") << server_ip << server_port);
    }

    ~TCPClient() {
        close(sockfd);  // 关闭客户端socket
    }

    // 发送数据到服务器
    void SendData(const std::string& data) {
        int n = send(sockfd, data.c_str(), data.size(), 0);
        if (n < 0) {
            LOG_ERROR("[log4]" << LOG4CPLUS_TEXT("发送数据给开发板失败"));
        }
    }

    // 从服务器接收数据
    void ReceiveData() {
        char buffer[BUFFER_SIZE];
        int n = recv(sockfd, buffer, BUFFER_SIZE, 0);
        if (n > 0) {
            buffer[n] = '\0';
            LOG_INFO("[log4]" << LOG4CPLUS_TEXT("收到来自板子的数据:")<< buffer);
        } else if (n == 0) {
            LOG_ERROR("[log4]" << LOG4CPLUS_TEXT("开发板程序已结束运行"));
            close(sockfd);
            exit(1);
        } else {
            LOG_ERROR("[log4]" << LOG4CPLUS_TEXT("收取开发板数据失败"));
        }
    }

private:
    int sockfd;
    struct sockaddr_in servaddr;
};

void monitorBoardSend(ThreadSafeQueue<std::string>& client2ServerQueue, 
                  TCPClient &client);
void monitorBoardReceive(ThreadSafeQueue<std::string>& server2ClientQueue, 
                  TCPClient &client);

#endif